#!/bin/bash
# Copyright 2024 Mengning Software All rights reserved.

# 默认值
NAME=DevStar-Studio
IMAGE_REGISTRY_USER=mengning997
IMAGE_NAME=devstar-studio
VERSION=latest    # DevStar Studio的默认版本为最新版本
PORT=80         # 设置端口默认值为 80
SSH_PORT=2222     # 设置ssh默认端口号2222
DATA_DIR=${HOME}/devstar_data
APP_INI=${DATA_DIR}/app.ini

# 错误处理函数  
error_handler() {  
    devstar help  
    exit 1  
}  

# 捕获错误信号  
trap 'error_handler' ERR 

# Exit immediately if a command exits with a non-zero status
set -e

# Colors for output
GREEN='\033[0;32m'
RED='\033[0;31m'
NC='\033[0m' # No Color

# Function to display success message
function success {
  echo -e "${GREEN}$1${NC}"
}

# Function to display failure message
function failure {
  echo -e "${RED}$1${NC}"
}

# Detect the OS type and install dependencies
function install_dependencies {
  # Install dependencies based on the OS type
  success "dependencies install begin: " 
  OS_ID=$(grep '^ID=' /etc/os-release | cut -d= -f2 | tr -d '"')

  case $OS_ID in
    ubuntu|debian)
      # 检查 Docker 是否已安装  
      if ! command -v docker &> /dev/null  
      then  
          echo "Installing Docker..."  
          # 更新包索引  
          sudo apt-get update  
          # 安装 Docker  
          sudo apt-get install -y docker.io 
          echo "Docker Installed！"  
      else  
          echo "Docker Installed, $(docker --version)"  
      fi  
      ;;
    centos)
    #   sudo yum update -y
    #   sudo yum install -y epel-release
    #   sudo yum groupinstall -y "Development Tools"
    #   sudo yum install -y yaml-cpp yaml-cpp-devel
      ;;
    fedora)
    #   sudo dnf update -y
    #   sudo dnf group install -y "Development Tools"
    #   sudo dnf install -y yaml-cpp yaml-cpp-devel
      ;;
    *)
      failure "Unsupported OS: $OS_ID"
      exit 1
      ;;
  esac
}

# Function to install
function install {
  install_dependencies
  if sudo docker pull mengning997/$IMAGE_NAME:$VERSION; then
      success "Successfully pulled mengning997/$IMAGE_NAME:$VERSION"  
  else 
    sudo docker pull devstar.cn/devstar/$IMAGE_NAME:$VERSION
    IMAGE_REGISTRY_USER=devstar.cn/devstar
  fi
  if sudo docker pull mengning997/webterminal:latest; then   
    sudo docker tag mengning997/webterminal:latest devstar.cn/devstar/webterminal:latest
    success "Successfully pulled mengning997/webterminal:latest renamed to devstar.cn/devstar/webterminal:latest"
  else 
    sudo docker pull devstar.cn/devstar/webterminal:latest
    success "Successfully pulled devstar.cn/devstar/webterminal:latest"  
  fi
  if sudo docker pull mengning997/act_runner:latest; then   
    sudo docker tag mengning997/act_runner:latest devstar.cn/devstar/act_runner:latest
    success "Successfully pulled mengning997/act_runner:latest renamed to devstar.cn/devstar/act_runner:latest"
  else 
    sudo docker pull devstar.cn/devstar/act_runner:latest
    success "Successfully pulled devstar.cn/devstar/act_runner:latest"  
  fi
}

# Function to start
function start {
  if [[ -z "$IMAGE_STR" ]]; then
      install
  fi
  # 创建devstar_data目录用于持久化存储DevStar相关的配置和用户数据
  mkdir -p $DATA_DIR
  sudo chown 1000:1000 $DATA_DIR
  sudo chmod 666 /var/run/docker.sock
  if [ ! -f "$APP_INI" ]; then  
      DOMAIN_NAME=$(hostname -I | awk '{print $1}')  
      echo "DOMAIN_NAME=$DOMAIN_NAME"
  else
      # 读取 DOMAIN 值  
      DOMAIN_NAME=$(grep -E '^\s*DOMAIN\s*=' "$APP_INI" | cut -d'=' -f2 | xargs)  
      # 检查是否成功读取到值  
      if [[ -z "$DOMAIN_NAME" ]]; then  
          DOMAIN_NAME="localhost"   
      fi   
      echo "DOMAIN_NAME=$DOMAIN_NAME"
  fi 
  # 启动devstar-studio容器
  stop
  if [[ -z "$IMAGE_STR" ]]; then  
      IMAGE_STR="$IMAGE_REGISTRY_USER/$IMAGE_NAME:$VERSION"     
  fi
  echo "image=$IMAGE_STR"
  sudo docker run --restart=always --name $NAME -d  -p $PORT:3000 -p $SSH_PORT:$SSH_PORT -v /var/run/docker.sock:/var/run/docker.sock -v ~/devstar_data:/var/lib/gitea -v ~/devstar_data:/etc/gitea $IMAGE_STR
  # 打开 `http://localhost:8080` 完成安装。
  success "-------------------------------------------------------"
  success "DevStar started in http://$DOMAIN_NAME:$PORT successfully!"
  success "-------------------------------------------------------"
  exit 0
}

# Function to stop
function stop {
  if [ $(docker ps -a --filter "name=^/${NAME}$" -q | wc -l) -gt 0 ]; then 
    sudo docker stop $NAME && sudo docker rm -f $NAME
  fi
  if [ $(docker ps -a --filter "name=^/devstar-studio$" -q | wc -l) -gt 0 ]; then 
    sudo docker stop devstar-studio && sudo docker rm -f devstar-studio
  fi
  if [ $(docker ps -a --filter "name=^/webterminal-" -q | wc -l) -gt 0 ]; then 
    sudo docker stop $(docker ps -a --filter "name=^/webterminal-" -q) && sudo docker rm -f $(docker ps -a --filter "name=^/webterminal-" -q)
  fi
  if [ $(docker ps -a --filter "name=^/runner-" -q | wc -l) -gt 0 ]; then 
    sudo docker stop $(docker ps -a --filter "name=^/runner-" -q) && sudo docker rm -f $(docker ps -a --filter "name=^/runner-" -q)
  fi       
}

# Function to logs
function logs {
  # 查看devstar-studio容器的运行日志
  sudo docker logs $NAME
}

# Function to clean
function clean {
  stop
  rm -rf $DATA_DIR
}

# Function to usage help
function usage {
  success "------------------------------------------------------------------------"
  success "DevStar usage help:"
  success "  help, -h, --help,     Help information"  
  success "  start                 Start DevStar Studio"  
  success "      --port=<arg>      Specify the port number (default port is 80)" 
  success "      --ssh-port=<arg>  Specify the ssh-port number (default ssh-port is 2222)" 
  success "      --version=<arg>   Specify the DevStar Studio Image Version (default verson is latest)" 
  success "      --image=<arg>     Specify the DevStar Studio Image example: devstar-studio:latest " 
  success "  stop                  Stop the running DevStar Studio"  
  success "  logs                  View the logs of the devstar-studio container"  
  failure "  clean                 Clean up the running DevStar Studio, including deleting user data. Please use with caution."  
  success "------------------------------------------------------------------------"
  exit 0
}

# Main script
case "$1" in
  -h|--help|help)
    usage
    ;;
  start)
    ARGS=$(getopt --long port::,ssh-port::,version::,image:: -- "$@")  
    if [ $? -ne 0 ]; then  
        failure "ARGS ERROR!"  
        exit 1  
    fi  
    eval set -- "${ARGS}"  
    # 处理选项  
    while true; do  
        case "$1" in  
            --port)  
                PORT="$2"  
                echo "The Port is: $PORT"  
                shift 2 ;; 
            --ssh-port)  
                SSH_PORT="$2"  
                echo "The SSH_Port is: $SSH_PORT"  
                shift 2 ;; 
            --version)  
                VERSION="$2"  
                echo "The DevStar Studio Image Version is: $VERSION"  
                shift 2 ;;
            --image)  
                IMAGE_STR="$2"  
                echo "The DevStar Studio Image: $IMAGE_STR"  
                shift 2 ;;    
            --)  
                shift  
                break ;;  
            *)  
                failure "Unrecognized option: $1"  
                exit 1 ;;  
        esac  
    done 
    start
    ;;
  stop)
    stop
    ;;
  logs)
    logs
    ;;
  clean)
    clean
    ;;
  *)
    # 获取当前脚本的文件名  
    script_name=$(basename "$0") 
    # 判断脚本名是否为 devstar  
    if [ "$script_name" != "devstar" ]; then  
        sudo mv ./install.sh /usr/bin/devstar
        rm -rf install.sh
        success "--------------------------------------"
        success "DevStar Studio installed successfully!"
        success "--------------------------------------"
        success "Copyright 2024 Mengning Software All rights reserved." 
        devstar help
    fi
    ;;
esac

